package com.icesoft.base.manager.config.listener;

import com.icesoft.base.manager.entity.manager.RelSysOrgOwner;
import com.icesoft.base.manager.entity.system.SysOrg;
import com.icesoft.base.manager.service.security.RelSysRoleOrgService;
import com.icesoft.base.manager.service.manager.RelSysOrgOwnerService;
import com.icesoft.base.manager.service.system.SysOrgService;
import com.icesoft.core.common.exception.CheckException;
import com.icesoft.core.dao.suppose.BaseModelListener;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class SysOrgDBListener extends BaseModelListener<SysOrg> {
    private RelSysOrgOwnerService relSysOrgOwnerService;
    private SysOrgService sysOrgService;
    private RelSysRoleOrgService relSysRoleOrgService;

    @Override
    public void prePersist(SysOrg model) {
        if (model.getPid() != 0) {
            SysOrg parent = sysOrgService.load(model.getPid());
            if (parent == null) {
                throw new CheckException("pid错误，未找到id为" + model.getPid() + "的org数据");
            }
            model.setCompanyId(parent.getCompanyId());
        }
    }

    @Override
    public void postPersist(SysOrg model) {
        RelSysOrgOwner owner = new RelSysOrgOwner();
        owner.setOrgId(model.getId());
        owner.setOwnerOrgId(model.getId());
        relSysOrgOwnerService.create(owner);

        int parentId = model.getPid();
        while (parentId != 0) {
            SysOrg parent = sysOrgService.load(parentId);
            RelSysOrgOwner relSysOrgOwner = new RelSysOrgOwner();
            relSysOrgOwner.setOrgId(parent.getId());
            relSysOrgOwner.setOwnerOrgId(model.getId());
            relSysOrgOwnerService.create(relSysOrgOwner);
            parentId = parent.getPid();
        }
    }

    @Override
    public void preRemove(SysOrg model) {
        relSysRoleOrgService.deleteOrgRelation(model.getId());
    }

    @Override
    public void postRemove(SysOrg model) {
        relSysOrgOwnerService.deleteOrgRelation(model.getId());
    }
}
